import { Module } from 'vuex'
import type { IRootState } from '../types'
import type { Ilogintype } from './types'
import {
  accountLoginRequest,
  requestUserInfoById,
  requestUserMenusById
} from '@/service/login/login'
import LocalCache from '@/utils/cache'
import router from '@/router'
import { mapMenusToPermissions, MenusToRoutes } from '@/utils/MenusToRoutes'

interface payloadType {
  zh: string
  mm: string
}
const loginModule: Module<Ilogintype, IRootState> = {
  namespaced: true,
  state() {
    return {
      token: '',
      userInfo: {},
      userMenus: [],
      perMissions: []
    }
  },
  mutations: {
    changeToken(state, token: string) {
      state.token = token
    },
    changeUserInfo(state, userinfo: any) {
      state.userInfo = userinfo
    },
    changeUserMenus(state, usermenu: any) {
      state.userMenus = usermenu

      // 做路由注册(usermenus映射到routes中)
      const routes = MenusToRoutes(usermenu) // 数组

      // 将routes添加到router.main.children中
      routes.forEach((route) => {
        router.addRoute('main', route)
      })

      // 获取用户按钮的权限
      const permissions = mapMenusToPermissions(usermenu)
      state.perMissions = permissions
    }
  },
  actions: {
    // async await 通过同步来实现异步
    async accountLoginAction(context, payload: payloadType) {
      // 1.实现登录逻辑
      const loginResult = await accountLoginRequest({
        name: payload.zh,
        password: payload.mm
      })

      const { id, token } = loginResult.data
      context.commit('changeToken', token)
      // 将token进行存储
      LocalCache.setCache('token', token)

      // 发送初始化请求,(拿到完整的department.role)
      // 在login中调用root的action 加上{ root: true}
      context.dispatch('getInitDataAction', null, { root: true })

      // 2.请求用户信息
      const userInfoResult = await requestUserInfoById(id)
      const userinfo = userInfoResult.data
      context.commit('changeUserInfo', userinfo)
      LocalCache.setCache('userinfo', userinfo)

      // 3.请求用户菜单
      const userMenusResult = await requestUserMenusById(userinfo.role.id) // id是userinfo里的id
      const usermenus = userMenusResult.data
      context.commit('changeUserMenus', usermenus)
      LocalCache.setCache('usermenus', usermenus)

      // 4.跳转主页
      router.push('/main')
    },
    // 刷新时调用
    initStoreAction(context) {
      const token = LocalCache.getCache('token')
      if (token) {
        context.commit('changeToken', token)
        // 发送初始化请求,(拿到完整的department.role)
        // 在login中调用root的action 加上{ root: true}
        context.dispatch('getInitDataAction', null, { root: true })
      }
      const userinfo = LocalCache.getCache('userinfo')
      if (userinfo) {
        context.commit('changeUserInfo', userinfo)
      }
      const usermenus = LocalCache.getCache('usermenus')
      if (usermenus) {
        context.commit('changeUserMenus', usermenus)
      }
    }
  }
}
export default loginModule
